package cn.modoumama.web.websocket;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

import cn.modoumama.socket.Message;

/**
 * Created by XuJijun on 2017-03-21.
 */
@ServerEndpoint("/my-websocket")
@Component
public class MyWebSocket {
	protected static final Logger logger = LoggerFactory.getLogger(MyWebSocket.class);

	private static int onlineCount = 0;

	private static Map<String,Session> sessiones = new HashMap<>();
	/**保存用户的长连接信息*/
	private static Map<String,String> userToSessiones = new HashMap<>();
	
	/**保存长连接对应的用户*/
	private static Map<String,String> sessionesToUsers = new HashMap<>();

	private Session session;
	
	
	@OnOpen
	public void onOpen(Session session) throws IOException{
		this.session = session;
		sessiones.put(session.getId(), session);
		incrOnlineCount();
		logger.info("new connection...current online count: {}", getOnlineCount());
	}

	@OnClose
	public void onClose() throws IOException{
		decOnlineCount();
		String sessionId = session.getId();
		String userId = sessionesToUsers.get(sessionId);
		sessiones.remove(session.getId());
		sessionesToUsers.remove(session.getId());
		userToSessiones.remove(userId);
		for(Session item : sessiones.values()){
			item.getBasicRemote().sendText("someone just closed a connection.");
		}
		logger.info("one connection closed...current online count: {}", getOnlineCount());
	}

	@OnMessage
	public void onMessage(String message, Session session) throws IOException {
		logger.info("message received: {}", message);
		Message msg = parse(message);
		
		if(StringUtils.isNotBlank(msg.getUserId())){
			String userId = msg.getUserId();
			userToSessiones.put(userId,session.getId());
			sessionesToUsers.put(session.getId(),userId);
			
			msg = new Message();
			msg.setToFrom(msg.getUserId());
			msg.setFromTo("系统");
			msg.setMessage("用户"+userId+"注册成功");
		}else{
			String userId = sessionesToUsers.get(session.getId());
			if(StringUtils.isNotBlank(userId)){
				msg.setFromTo(userId);
				if(StringUtils.isNotBlank(msg.getToFrom())){
					sendMsg(msg);
				}else{
					/** 业务方法  */
					msg.setMessage("服务器返回给用户"+userId+"的消息");
				}
			}else{
				msg.setMessage("找不到该用户");
			}
		}
		
		sendMsg(JSON.toJSONString(msg));
		
	}
	
	 private Message parse(String message){
		 Message msg = null;
        if (StringUtils.isNotEmpty(message)) {
			try {
				msg = JSON.parseObject(message, Message.class);
			} catch (Exception e) {
				msg = new Message();
				msg.setMessageType(Message.HEART_TEXT);
				msg.setMessage(message);
			}
        }
        return msg;
   }
	 
	 
	 private void sendMsg(String message) throws IOException{
		 sendMsg(session, message);
	 }
	 
	 private static void sendMsg(Session session, String message) throws IOException{
		 if(session != null){
			 session.getBasicRemote().sendText(message);
		 }
	 }
	 
	 public static void sendMsg(Message message){
		 if (StringUtils.isNotEmpty(message.getToFrom())) {
			String sessionId = userToSessiones.get(message.getToFrom());
			Session session = sessiones.get(sessionId);
			try {
				 sendMsg(session, JSON.toJSONString(message));
			} catch (Exception e) {
				logger.error(e.getMessage());
			}
	     }
	 }
	

	public static synchronized int getOnlineCount(){
		return MyWebSocket.onlineCount;
	}

	public static synchronized void incrOnlineCount(){
		MyWebSocket.onlineCount++;
	}

	public static synchronized void decOnlineCount(){
		MyWebSocket.onlineCount--;
	}
}
